const explain = require("explain")
const uniID = require('uni-id')

module.exports = class studyRecord extends explain.service {
	async saveRecord(params) {
		const payload = await uniID.checkToken(params.token)
		if (payload.code) {
			return payload
		}
		const db = uniCloud.database()
		if (params._id) {
			const {
				data
			} = await db.collection('study-records').where({
				_id: params._id
			}).get()
			const isComplete = data[0].is_complete

			const res = await db.collection('study-records').doc(params._id).update({
				user_id: payload.uid,
				video_id: params.video_id,
				course_id: params.course_id,
				current_time: params.current_time,
				duration: params.duration,
				is_complete: !isComplete ? params.is_complete : isComplete,
				updated_at: new Date().getTime()
			})

			// 如果学完整个课程，增加培训记录
			if (isComplete && params.is_complete) {
				const completeCount = await db.collection('study-records').where({
					user_id: payload.uid,
					course_id: params.course_id
				}).count().total

				const courseCount = await db.collection('videos').where({
					course_id: params.course_id
				}).count().total

				let trainingRecords = payload.userInfo.paramedic_profile.training_records
				if (!trainingRecords) {
					trainingRecords = []
				}
				if (completeCount === courseCount) {
					const courses = await db.collection('courses').where({
						_id: params.course_id
					}).get()
					const courseData = courses.data[0]
					courseData.completed_at = new Date().getTime()
					const courseIndex = trainingRecords.findIndex(item => item._id === courseData._id)
					if (courseIndex > -1) {
						trainingRecords.splice(courseIndex, 1, courseData)
					} else {
						trainingRecords.push(courseData)
					}


					await db.collection('uni-id-users').where({
						_id: payload.uid
					}).update({
						paramedic_profile: {
							training_records: trainingRecords,
						}
					})
				}
			}
			return res
		} else {
			return await db.collection('study-records').add({
				user_id: payload.uid,
				video_id: params.video_id,
				course_id: params.course_id,
				current_time: params.current_time,
				duration: params.duration,
				is_complete: params.is_complete,
				updated_at: new Date().getTime(),
				created_at: new Date().getTime()
			})
		}
	}
}
